package longrise.phone.com.bjjt_henan.compensate;

import android.app.Activity;
import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.TextView;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.SDKInitializer;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.Marker;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.MyLocationConfiguration;
import com.baidu.mapapi.map.MyLocationConfiguration.LocationMode;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mobstat.StatService;
import com.longrise.LEAP.Base.Objects.EntityBean;
import com.longrise.android.loaddata.newloaddata.LoadDataManagerCar;
import com.longrise.android.loaddata.newloaddata.LoadDataManagerFather;
import com.longrise.bjjt.BaseApplication;
import com.longrise.bjjt.util.UiUtil;

import longrise.phone.com.bjjt_henan.Constant.URLConstant;
import longrise.phone.com.bjjt_henan.R;

/**
 * Created by Administrator on 2016/5/17.
 */
public class BaiduMapActivity extends Activity {

    private MapView mapView;

    private BaiduMap baiduMap;
    private BaseApplication mApplication;
    // 定位相关
    private LocationClient locationClient;

    private BroadcastReceiver mReceiver;
    private Dialog processDialog;
    private BitmapDescriptor descriptor;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.baidumap_main);
        this.mApplication = (BaseApplication) BaiduMapActivity.this.getApplicationContext();
        initViews();
        initValues();
        //查询接口将覆盖物显示进来
        searchpoint();
    }

    /**
     * 查询维修点，将覆盖物显示
     */
    private void searchpoint() {
        BaseApplication application = (BaseApplication) BaiduMapActivity.this
                .getApplicationContext();
        String url = application.getServerUrl();
        EntityBean bean = new EntityBean();
        bean.put("username", application.getKckpName());//用户名
        bean.put("token", application.getToken());
        processDialog = UiUtil.showProcessDialog(BaiduMapActivity.this, "加载数据中...");

        LoadDataManagerCar.getInstance(BaiduMapActivity.this).callService(null, url,
                URLConstant.KCKPSEARCHCPSCENTER, bean, new LoadDataManagerFather.OnRequestCompleteListener() {
                    @Override
                    public void onSuccess(String key, String service, Object result) {
                        if (null != processDialog) {
                            if (processDialog.isShowing()) {
                                processDialog.dismiss();
                            }
                        }
                        EntityBean bean = (EntityBean) result;
                        String restate = bean.getString("restate");
                        String redes = bean.getString("redes");
                        EntityBean[] dataBean = bean.getBeans("data");
                        if ("1".equals(restate)) {
                            for (int x = 0; x < dataBean.length; x++) {
                                showNearbyPosition(Double.parseDouble(dataBean[x].getString("gisp_x")), Double.parseDouble(dataBean[x].getString("gisp_y")), dataBean[x].getString("centername"));
                            }
                            return;
                        } else {
                            UiUtil.showToast(BaiduMapActivity.this, redes);
                        }
                    }

                    @Override
                    public void onError(String key, String service, LoadDataManagerFather.ResultType resultType) {
                        if (null != processDialog) {
                            if (processDialog.isShowing()) {
                                processDialog.dismiss();
                            }
                        }
                    }

                    @Override
                    public void onFinished(String key, String service) {
                        if (null != processDialog) {
                            if (processDialog.isShowing()) {
                                processDialog.dismiss();
                            }
                        }
                    }
                });
    }

    //显示附近的理赔中心，设置点击事件,附近的地点的
    private void showNearbyPosition(double x, double y, final String message) {
        //定义Maker坐标点
        LatLng point = new LatLng(x, y);
        //构建MarkerOption，用于在地图上添加Marker
        OverlayOptions option = new MarkerOptions()
                .position(point)
                .icon(descriptor);
        //在地图上添加Marker，并显示
        baiduMap.addOverlay(option);
        baiduMap.setOnMarkerClickListener(new BaiduMap.OnMarkerClickListener() {
            @Override
            public boolean onMarkerClick(Marker marker) {
                UiUtil.showToast(BaiduMapActivity.this, message);
                return false;
            }
        });
    }

    private void initViews() {
        // 设置标题
        TextView titleTView = (TextView) findViewById(R.id.tv_title);
        titleTView
                .setText(getResources().getString(R.string.traffic_condition));
        findViewById(R.id.hn_btn_back).setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View arg0) {
                finish();
            }
        });

        mapView = (MapView) findViewById(R.id.bmapView);
        // 隐藏百度logo
        mapView.removeViewAt(1);
        baiduMap = mapView.getMap();
        // 设置地图状态
        MapStatusUpdate msu = MapStatusUpdateFactory.zoomTo(16.0f);
        baiduMap.setMapStatus(msu);
        // // 开启定位图层
        baiduMap.setMyLocationEnabled(true);
        // 实时路况图层
        baiduMap.setTrafficEnabled(true);

        // 注册广播
        IntentFilter iFilter = new IntentFilter();
        iFilter.addAction(SDKInitializer.SDK_BROADTCAST_ACTION_STRING_PERMISSION_CHECK_ERROR);
        iFilter.addAction(SDKInitializer.SDK_BROADCAST_ACTION_STRING_NETWORK_ERROR);
        mReceiver = new SDKReceiver();
        registerReceiver(mReceiver, iFilter);
    }

    /**
     * 监听 SDK key 验证以及网络异常广播
     */
    public class SDKReceiver extends BroadcastReceiver {
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action
                    .equals(SDKInitializer.SDK_BROADTCAST_ACTION_STRING_PERMISSION_CHECK_ERROR)) {
                // key 验证失败，相应处理
                UiUtil.showToast(BaiduMapActivity.this, getResources()
                        .getString(R.string.key_error));
            } else if (action
                    .equals(SDKInitializer.SDK_BROADCAST_ACTION_STRING_NETWORK_ERROR)) {
                // 网络异常
                UiUtil.showToast(BaiduMapActivity.this, getResources()
                        .getString(R.string.net_error));
            }
        }
    }

    private void initValues() {
        // 设置定位图标
        descriptor = BitmapDescriptorFactory
                .fromResource(R.drawable.icon_marka);
        baiduMap.setMyLocationConfigeration(new MyLocationConfiguration(
                LocationMode.NORMAL, true, descriptor));
        // 定位初始化 TODO 暂时不定位
        locationClient = new LocationClient(this);
        locationClient.registerLocationListener(listener);
        LocationClientOption option = new LocationClientOption();
        option.setOpenGps(true);// 打开gps
        option.setCoorType("bd09ll");// 设置经纬度测算类型
        option.setScanSpan(100000);// 定位请求间隔时间为10000ms
        option.setAddrType("all"); // 设置返回类型，all表示返回所有的数据
        locationClient.setLocOption(option);
        locationClient.start();
    }

    private BDLocationListener listener = new BDLocationListener() {
        @Override
        public void onReceiveLocation(BDLocation location) {
            if (location == null || mapView == null) {
                return;
            }
            // 显示定位位置
            MyLocationData locData = new MyLocationData.Builder()
                    .accuracy(location.getRadius())
                    .direction(location.getDirection())
                    .latitude(location.getLatitude())
                    .longitude(location.getLongitude()).build();
            baiduMap.setMyLocationData(locData);

            LatLng ll = new LatLng(location.getLatitude(),
                    location.getLongitude());
            // 以动画方式更新地图状态
            MapStatusUpdate status = MapStatusUpdateFactory.newLatLng(ll);
            baiduMap.animateMapStatus(status);
        }

        @SuppressWarnings("unused")
        public void onReceivePoi(BDLocation poiLocation) {

        }
    };

    @Override
    protected void onDestroy() {
        if (locationClient != null) {
            locationClient.stop();
        }
        // 关闭定位图层
        if (baiduMap != null) {
            baiduMap.setMyLocationEnabled(false);
        }
        if (mapView != null) {
            mapView.onDestroy();
        }
        mapView = null;
        unregisterReceiver(mReceiver);
        super.onDestroy();
    }

    @Override
    public void onResume() {
        mapView.onResume();
        // 启动服务
        if (locationClient != null) {
            locationClient.start();
        }
        StatService.onResume(this);
        super.onResume();
    }

    @Override
    public void onPause() {
        mapView.onPause();
        if (locationClient != null) {
            locationClient.stop();
        }
        StatService.onPause(this);
        super.onPause();
    }
}
